package com.prim.background;

/**
 * 解决：隐式逸出 -- 注册监听事件
 */
public class MultiThreadError7 {
    int count;

    public EventListener listener;

    public MultiThreadError7(MySource mySource) {
        listener = new EventListener() {
            @Override
            public void onEvent(Event event) {
                System.out.println();
                System.out.println("我得到的数字是:" + count);
            }
        };
        //对象还没有初始化完毕 就调用了EventListener 导致获得的count为0
        for (int i = 0; i < 10000; i++) {
            System.out.print(i);
        }
        count = 100;
    }

    public static MultiThreadError7 getInstance(MySource source) {
        //先进行初始化在注册监听
        MultiThreadError7 multiThreadError7 = new MultiThreadError7(source);
        source.registerListener(multiThreadError7.listener);
        return multiThreadError7;
    }

    public static void main(String[] args) {
        MySource mySource = new MySource();
        new Thread(new Runnable() {
            @Override
            public void run() {
//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                mySource.eventCome(new Event() {
                });
            }
        }).start();
        MultiThreadError7.getInstance(mySource);
    }

    static class MySource {
        private EventListener eventListener;

        void registerListener(EventListener eventListener) {
            this.eventListener = eventListener;
        }

        void eventCome(Event e) {
            if (eventListener != null) {
                eventListener.onEvent(e);
            } else {
                System.out.println("还未初始化完毕");
            }
        }
    }

    interface EventListener {
        void onEvent(Event event);
    }

    interface Event {

    }
}
